/**
 * @Name:
 * @Author:
 * @Desc:  关于滚动条的一些事件
 * @Date: 2020-12-04 09:25:34
 */
import React, { Component } from "react";
import { Title } from "@/component";
import $ from "jquery";
import { scrollTo, averageArr } from "@/utils";
import styles from "./styles.module.less";
const list = [
  { height: 220, id: "aa", name: "aa" },
  { height: 120, id: "bb", name: "bb" },
  { height: 420, id: "cc", name: "cc" },
  { height: 270, id: "dd", name: "dd" }
];
class Scroll extends Component {
  state = {
    barWidth: 0,
    scrollId: list[0].id
  };
  componentDidMount() {
    //监听滚动条
    window.addEventListener("scroll", this.scroll);
    this.scroll();
  }
  componentWillUnmount() {
    //卸载事件
    window.removeEventListener("scroll", this.scroll);
  }
  /**
   * @name scroll
   * @desc 监听滚动条 支持IE7及以上
   */
  scroll = () => {
    //窗口高度
    let windowHeight = document.documentElement.clientHeight;
    //滚动条滑动距离
    let scrollHeight = document.documentElement.scrollTop;
    //页面文档总体高度
    let documentHeight = document.documentElement.scrollHeight;
    //百分比 = (窗口高度 + 滚动条滑动距离) /  页面文档总体高度
    let percent = scrollHeight > 0 ? (scrollHeight / (documentHeight - windowHeight)) * 100 : 0;
    this.setState({ barWidth: percent });
  };
  /**
   * @name scrollChange
   * @param {String} id 指定位置ID
   * @description 滚动到指定位置
   */
  scrollChange = (id) => {
    scrollTo({ containerId: "list", targetElementId: id, offset: 2 });
  };
  test = () => {
    let arr = [0, 1, 2, 3, 4];

    console.log("aaaaaaaaa", averageArr(arr, 3));
  };
  render() {
    const { scrollId } = this.state;
    return (
      <div className={styles.container}>
        {this.test()}
        <div className={styles.topbar} style={{ width: `${this.state.barWidth}%` }}></div>
        <div className={styles.block}>
          <Title text="关于滚动条的一些事件" />
        </div>
        <div style={{ padding: "10px" }}>
          {list.map((v) => (
            <div className={v.id === scrollId ? styles.li_btn_active : styles.li_btn} onClick={() => this.scrollChange(v.id)}>
              {v.name}
            </div>
          ))}
        </div>
        <div>
          <ul className={styles.ul} id="list">
            {list.map((v) => (
              <li className={styles.li} style={{ height: v.height }} id={v.id}>
                <h1>{v.name}</h1>
              </li>
            ))}
          </ul>
        </div>
      </div>
    );
  }
}
export default Scroll;
